package com.xbq.exceleditor.ui

import android.app.Activity
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import com.xbq.exceleditor.BuildConfig
import com.xbq.exceleditor.R
import com.xbq.exceleditor.databinding.FragmentLoginBinding
import com.xbq.exceleditor.utils.validateEmpty
import com.xbq.exceleditor.utils.value
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.net.UserRepository
import com.xbq.xbqsdk.util.click.onDebouncedClick
import com.xbq.xbqsdk.util.coroutine.launch
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2020-10-24
 * Description:
 */
@AndroidEntryPoint
class LoginFragment : VBFragment<FragmentLoginBinding>() {
    @Inject
    lateinit var userRepository: UserRepository

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initDebug()
        binding.let {
            it.appIcon.setImageResource(AppUtils.getAppIconId())
//            it.btnBack.onDebouncedClick { activity?.finish() }
            it.btnGoRegister.onDebouncedClick{
                (requireActivity() as LoginActivity?)?.showRegister()
            }
            it.btnLogin.onDebouncedClick{login()}
            it.ckbReadPrivacyAlready.setOnCheckedChangeListener { buttonView, isChecked ->
                binding.btnLogin.isEnabled=isChecked
            }
            CkbReadPrivacySetup(it.tvPrivacy).setup()
        }
    }

    fun initDebug(){
        if(BuildConfig.DEBUG){
            binding.etPhoneNumber.setText("test")
            binding.etPassword.setText("123")
        }
    }

    fun login(){
        launch {
            val userName = binding.etPhoneNumber.value()
            val password = binding.etPassword.value()
            if(validateEmpty(userName,R.string.pls_type_user_name)
                && validateEmpty(password,R.string.pls_type_password)){
                val res = userRepository.login(userName,password)
                if(res.success()){
                    ToastUtils.showShort(R.string.login_successfull)
                    activity?.setResult(Activity.RESULT_OK)
                    activity?.finish()
                }else{
                    ToastUtils.showShort(res.message)
                }
            }
        }
    }
}